package org.example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Test2 {
    //leetcode 三数之和 https://leetcode.cn/problems/3sum/description/?envType=study-plan-v2&envId=top-interview-150
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> list = new ArrayList<>();
        Arrays.sort(nums);
        int n = nums.length;
        for (int i = 0; i <= n-3; i++) {
            if (nums[i] > 0) break;
            if (i >= 1 && nums[i] == nums[i-1]) continue;
            int target = -nums[i];
            int left = i + 1, right = n-1;
            while (left < right) {
                int sum = nums[left] + nums[right];
                if (sum == target) {
                    list.add(Arrays.asList(nums[i],nums[left],nums[right]));
                    while (left < right && nums[right] == nums[right-1]) right--;
                    while (left < right && nums[left] == nums[left + 1]) left++;
                    left++;
                    right--;
                }else if (sum > target) {
                    right--;
                }else {
                    left++;
                }
            }
        }
        return list;
    }
}
